/*
 * TWIMaster.c
 *
 * Created: 3/17/2012 1:42:58 PM
 *  Author: Unithra.C
 */ 

#include <avr/io.h>
#include "inc\Uart.h"

void TWI_init_master(void) // Function to initialize master
{
	TWBR=32;	// Bit rate at 100kHz //0x02 for 400khz
	TWSR=(0<<TWPS1)|(0<<TWPS0);	// Setting pre-scaler bits
	// SCL freq= F_CPU/(16+2(TWBR).4^TWPS)
}
 
void TWI_start(void)
{
	// Clear TWI interrupt flag, Put start condition on SDA, Enable TWI
	TWCR= (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);	
	while(!(TWCR & (1<<TWINT))); // Wait till start condition is transmitted
	while((TWSR & 0xF8)!= 0x08); // Check for the acknowledgement
}
 
void TWI_repeated_start(void)
{
	// Clear TWI interrupt flag, Put start condition on SDA, Enable TWI
	TWCR= (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);	
	while(!(TWCR & (1<<TWINT))); // wait till restart condition is transmitted
	while((TWSR & 0xF8)!= 0x10); // Check for the acknowledgement
}
 
void TWI_write_address(unsigned char data)
{
	TWDR=data;	// Address and write instruction
	TWCR=(1<<TWINT)|(1<<TWEN);    // Clear TWI interrupt flag,Enable TWI
	while (!(TWCR & (1<<TWINT))); // Wait till complete TWDR byte transmitted
	while((TWSR & 0xF8)!= 0x18);  // Check for the acknowledgement
}

 
void TWI_read_address(unsigned char data)
{
	TWDR=data;	// Address and read instruction
	TWCR=(1<<TWINT)|(1<<TWEN);    // Clear TWI interrupt flag,Enable TWI
	while (!(TWCR & (1<<TWINT))); 
	while((TWSR & 0xF8)!= 0x40);  // Check for the acknowledgement
	TWCR=(0 << TWSTO)|(0 << TWSTA)|(1<<TWINT)|(0<<TWEA)|(1<<TWEN);    // Clear TWI interrupt flag,Enable TWI
	while((TWSR & 0xF8)!= 0x58);  // wait for data to be received
}
 
void TWI_write_data(unsigned char data)
{
	TWDR=data;	// put data in TWDR
	TWCR=(1<<TWINT)|(1<<TWEN);    // Clear TWI interrupt flag,Enable TWI
	while (!(TWCR & (1<<TWINT))); // Wait till complete TWDR byte transmitted
	while((TWSR & 0xF8) != 0x28); // Check for the acknowledgement
}
 
  
void TWI_stop(void)
{
	// Clear TWI interrupt flag, Put stop condition on SDA, Enable TWI
	TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWSTO);	
	while(!(TWCR & (1<<TWSTO)));  // Wait till stop condition is transmitted
}

void TWI_Reset(void)
{
	int i = 0;
	TWCR &= ~(1 << TWEN);
	for(i=0;i<5000;i++);
	TWCR = (1 << TWEN);	
}